package webs.servlet.ServletDemoTwo;
//演示Request对象的获取请求参数的通用方法

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

@WebServlet("/demo7")
public class servletTest_Seven extends HttpServlet
{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        //解决post方式中文乱码,页面格式是什么编码，就设置成哪种格式
        req.setCharacterEncoding("UTF-8");
        //根据参数名称获取参数值
        System.out.println("getParameter()方法：");
        String name=req.getParameter("username");
        String password=req.getParameter("password");
        System.out.println("name-----"+name);
        System.out.println("password-----"+password);
        System.out.println("--------------");

        //根据参数名称获取参数值；复选框的值
        System.out.println("getParameterValues()方法");
        String[] hobbies=req.getParameterValues("hobby");
        for(String values:hobbies)
            System.out.println(values);
        System.out.println("---------------");

        //获取所有请求参数的名称,封装为枚举类型
        System.out.println("getParameterNames()方法");
        Enumeration<String> parameterNames=req.getParameterNames();
        while(parameterNames.hasMoreElements())
        {
            String parametername=parameterNames.nextElement();
            System.out.println(parametername);
            String[] parameterValues=req.getParameterValues(name);
            System.out.println("-----");
        }
        System.out.println("---------------");

        //获取所有请求参数的名称，封装为Map集合
        System.out.println("getParameterMap()方法");
        Map<String,String[]> parameterMap=req.getParameterMap();
        Set<String> keySet=parameterMap.keySet();
        for(String names:keySet)
        {
            System.out.println(names);
            String[] values=req.getParameterValues(names);
            for(String value:values)
                System.out.println(value);
            System.out.println("-----");
        }
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        this.doPost(req,resp);
    }
}
